package com.liucxu.jiandanl.Http;

import com.liucxu.jiandanl.Interface.RequestCallbackInterface;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * 网络请求管理类
 * Created by liuchenxu on 2016/8/3.
 */
public class RequestManager {
    private static OkHttpClient client;

    private static void initOKHttpClient() {
        if (client == null) {
            synchronized (RequestManager.class) {
                client = new OkHttpClient();
                client.setConnectTimeout(15, TimeUnit.SECONDS);
                client.setReadTimeout(10, TimeUnit.SECONDS);
                client.setWriteTimeout(10, TimeUnit.SECONDS);
            }
        }
    }

    /**
     * Get网络请求
     *
     * @param url
     * @param call
     */
    public static void GET(String url, final RequestCallbackInterface call) {
        if (client == null) {
            initOKHttpClient();
        }
        Request.Builder builder = new Request.Builder().url(url);
        Request request = builder.build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                call.onFail();
            }

            @Override
            public void onResponse(Response response) throws IOException {
                call.onSuccess(response.body().string());
            }
        });
    }

    /**
     * Post网络请求
     *
     * @param url
     * @param params
     * @param call
     */
    public static void POST(String url, HashMap<String, String> params, final RequestCallbackInterface call) {
        if (client == null) {
            initOKHttpClient();
        }
        Request.Builder builder = new Request.Builder().url(url);
        FormEncodingBuilder encodingBuilder = new FormEncodingBuilder();
        if (params != null && params.size() > 0) {
            for (String key : params.keySet()) {
                encodingBuilder.add(key, params.get(key));
            }
        }
        RequestBody formBody = encodingBuilder.build();
        builder.post(formBody);
        Request request = builder.build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                call.onFail();
            }

            @Override
            public void onResponse(Response response) throws IOException {
                call.onSuccess(response.body().string());
            }
        });
    }
}
